package com.zjj.lbw.algorithm.sort;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author zhanglei.zjj
 * @description 桶排序
 * @date 2023/3/26 16:30
 */
public class BucketSort {
    public static void main(String[] args) {
        List<Integer> unsortedList = Arrays.asList(35, 23, 48, 9, 16, 24, 5, 11, 32, 17);
        System.out.println("排序前元素顺序为；" + unsortedList);
        List<Integer> sortedList = bucketSort(unsortedList, 5);
        System.out.println("排序后的元素顺序为：" + sortedList);

    }

    static List<Integer> bucketSort(List<Integer> list, int bucketCap) {
        if (Objects.isNull(list) ||list.size() == 0) {
            return new ArrayList<>();
        }

        // 找最大值、最小值
        int min = list.get(0);
        int max = list.get(0);
        for (int item : list) {
            if (item < min) {
                min = item;
            }
            if (item > max) {
                max = item;
            }
        }

        // 确定桶的数量
        int bucketSize = (max - min) / bucketCap + 1;

        // 用list来表示桶
        List<List<Integer>> buckets = new ArrayList<>(bucketSize);
        // 初始化桶
        for (int i = 0; i < bucketSize; i++) {
            buckets.add(new ArrayList<>());
        }

        // 将原数组放到桶中
        for (int i = 0; i < list.size(); i++) {
            buckets.get((list.get(i) - min) / bucketCap).add(list.get(i));
        }
        System.out.println("分桶情况为：" + buckets);

        List<Integer> resultList = new ArrayList<>();
        // 每个桶再排序
        for (List<Integer> bucket : buckets) {
            // 递归终止条件
            if (bucketCap == 1) {
                resultList.addAll(bucket);
            } else {
                if (bucketSize == 1) {
                    bucketCap --;
                }

                List<Integer> tempList = bucketSort(bucket, bucketCap);
                resultList.addAll(tempList);
            }
        }
        return resultList;
    }
}
